package com.cl.cloud.auth.config;

import com.cl.cloud.auth.exception.CustomWebResponseExceptionTranslator;
import com.cl.cloud.auth.handler.ResourceAccessDeniedHandler;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;

/**
 * 可以配置那些请求地址需要认证，哪些请求地址不需要认证
 * @description: 自定义资源服务器配置类
 * @author: liuzijian
 * @time: 2022-05-10 14:14
 */
@Configuration
@EnableResourceServer // 配置资源服务器
@AllArgsConstructor
public class CustomResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    private final CustomWebResponseExceptionTranslator customWebResponseExceptionTranslator;

    /**
     * 与WebSecurityConfigurerAdapter中的配置不一样 这里配置的是spring security oauth2的
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.formLogin();//设置formLogin的认证方式   Spring Security支持两种认证方式：formLogin()和httpBasic()
        http.authorizeRequests()
                .antMatchers(
                        "/oauth/**"
                ).permitAll()//配置不需要认证的url
                .anyRequest().authenticated();//除上面的url，所有的url都需要认证
        http.csrf().disable();//禁用跨域请求保护

        //不添加 X-Frame-Options 到请求头 意思是可以在iframe上调用
        http.headers().frameOptions().disable();

        //自定义资源异常处理
        http.exceptionHandling()
                .authenticationEntryPoint(new ResourceAccessDeniedHandler(customWebResponseExceptionTranslator));
    }

}
